﻿using System.Data;

namespace Tools
{
    public static class DataGridViewDataGet
    {

        /// <summary>
        /// 获取 DataGridView 的所有数据为 DataTable
        /// </summary>
        public static DataTable ToDataTable(this DataGridView dataGridView)
        {
            var dt = new DataTable();

            // 添加列
            foreach (DataGridViewColumn column in dataGridView.Columns)
            {
                if (column.ValueType == null)
                {
                    dt.Columns.Add(column.Name, typeof(object));
                }
                else
                {
                    dt.Columns.Add(column.Name, column.ValueType);
                }
            }

            // 添加行数据
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                if (row.IsNewRow) continue;

                DataRow dr = dt.NewRow();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dr[cell.ColumnIndex] = cell.Value ?? DBNull.Value;
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }
    }
}
